﻿using System.Configuration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using MvcApplicationDataHound.TSD_Mappings;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Tool.hbm2ddl;
using NHibernate;

namespace MvcApplicationDataHound.Mappings
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    InitializeSessionFactory();
                }
                return _sessionFactory;
            }
        }

        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2012 //Tells NHibernate to use the SQL Server Driver
                                        //.ConnectionString(ConfigurationManager.ConnectionStrings["DataHoundDB"].ConnectionString)
                                        .ConnectionString("Server=.\\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;")
                
                )
                .Mappings(m =>
                        m.FluentMappings
                        .AddFromAssemblyOf<Car>())
                .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                        .Create(true, true))
                .BuildSessionFactory();
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
    //
    public class MsSqlConfiguration : PersistenceConfiguration<MsSqlConfiguration, MsSqlConnectionStringBuilder>
    {
        protected MsSqlConfiguration()
        {
            Driver<SqlClientDriver>();
        }

        public static MsSqlConfiguration MsSql7
        {
            get { return new MsSqlConfiguration().Dialect<MsSql7Dialect>(); }
        }

        public static MsSqlConfiguration MsSql2000
        {
            get { return new MsSqlConfiguration().Dialect<MsSql2000Dialect>(); }
        }

        public static MsSqlConfiguration MsSql2005
        {
            get { return new MsSqlConfiguration().Dialect<MsSql2005Dialect>(); }
        }

        public static MsSqlConfiguration MsSql2008
        {
            get { return new MsSqlConfiguration().Dialect<MsSql2008Dialect>(); }
        }

        public static MsSqlConfiguration MsSql2012
        {
            get { return new MsSqlConfiguration().Dialect<MsSql2012Dialect>(); }
        }
    }
    //
}